package com.polaris.live.im.sfs.processor.impl

import android.os.Bundle
import com.google.firebase.analytics.ktx.analytics
import com.google.firebase.ktx.Firebase
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.util.JsonUtils
import com.polaris.live.im.sfs.COMMAND_NOTICE_EVENT
import com.polaris.live.im.sfs.bean.pusher.PusherNoticeMessage
import com.polaris.live.im.sfs.bean.pusher.TrackEventMessage
import com.polaris.live.im.sfs.core.bean.DataArgument
import com.polaris.live.im.sfs.processor.MessageProcessSignal
import com.polaris.live.im.sfs.processor.impl.system.AbstractExcludeMessageProcessor
import com.polaris.live.utils.postEvent
import kotlinx.coroutines.withContext

/**
 * 通知事件
 *
 * @author Created by lucas on 2023/11/23 17:43
 * @since 1.0.0
 */
class NoticeEventMessageProcessor : AbstractExcludeMessageProcessor() {

    override fun shouldProcess(type: Int, command: String): Boolean {
        return command == COMMAND_NOTICE_EVENT
    }

    override suspend fun process(type: Int, command: String, argument: DataArgument): MessageProcessSignal {
        return exclude(type, argument) {
            super.process(type, command, argument)
        }
    }

    override suspend fun handle(type: Int, command: String, argument: DataArgument) {
        val data = argument.getData<PusherNoticeMessage>() ?: return
        val message = JsonUtils.fromJson<TrackEventMessage>(data.content) ?: return

        withContext(CoroutineScopeManager.mainDispatcher) {
            message.events.forEach { event ->
                val bundle = Bundle()
                event.params.forEach {
                    bundle.putString(it.name, it.value)
                }

                if (event.trackType == 0) {
                    Firebase.analytics.postEvent(event.event, bundle)
                }
            }
        }
    }
}